//
//  PopoverAnimator.swift
//  CXCWeibo
//
//  Created by cxc on 15/6/27.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit

class PopoverAnimator: NSObject,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning{
    
    var presentFrame = CGRectZero
    
    var isPresented = false
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        let pc = PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting)
        pc.presentFrame = presentFrame
        
        return pc
    }
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 1.2
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        let toVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        print(fromVC)
        print(toVC)
        if isPresented {
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
            transitionContext.containerView()?.addSubview(toView!)
            toView?.transform = CGAffineTransformMakeScale(1.0, 0)
            toView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
            toView?.layer.anchorPointZ  = 0.5
            UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
                toView?.transform = CGAffineTransformIdentity
                }, completion: { (_) -> Void in
                    transitionContext.completeTransition(true)
            })
            
        }else{
            let fromVC = transitionContext.viewForKey(UITransitionContextFromViewKey)!
            fromVC.removeFromSuperview()
            
            transitionContext.completeTransition(true)
        }
    }
}
